import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet } from 'react-native';
import { Input, withTheme } from 'react-native-elements';

class InputClearable extends React.Component {

    static propTypes = {
        ...Input.propTypes,
        clear: PropTypes.bool,
        clearColor: PropTypes.string,
        refInput: PropTypes.func
    }

    render() {

        const { clear, clearColor, rightIcon, theme, refInput, ...rest } = this.props;

        return (
            <Input
                {...rest}
                ref={ipt => {
                    this.ipt = ipt;
                    if (refInput && typeof refInput === 'function') {
                        refInput(ipt);
                    }
                }}
                rightIcon={
                    clear && rest.value ? {
                        type: 'entypo',
                        name: 'circle-with-cross',
                        color: clearColor || theme.colors.grey3,
                        onPress: () => {
                            if (rest.onChangeText) {
                                rest.onChangeText('');
                            } else {
                                this.ipt.clear();
                            }
                        }
                    } : rightIcon
                }
                inputStyle={StyleSheet.flatten([{ padding: 0 }, rest.inputStyle])}
            />
        );
    }
}

export default withTheme(InputClearable);